package com.tencent.qcloud.timchat.ui.customview

import android.app.Activity
import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.Window
import android.widget.Toast

import com.tencent.imsdk.TIMCallBack
import com.tencent.qcloud.presentation.business.LoginBusiness
import com.tencent.qcloud.timchat.R
import com.tencent.qcloud.timchat.model.FriendshipInfo
import com.tencent.qcloud.timchat.model.GroupInfo
import com.tencent.qcloud.timchat.model.UserInfo
import com.tencent.qcloud.timchat.ui.SplashActivity
import com.tencent.qcloud.tlslibrary.service.TlsBusiness

class DialogActivity : Activity(), View.OnClickListener {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        setContentView(R.layout.activity_dialog)
        setFinishOnTouchOutside(false)
    }

    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */
    override fun onClick(v: View) {
        when (v.id) {
            R.id.btnOk -> LoginBusiness.loginIm(UserInfo.getInstance().id, UserInfo.getInstance().userSig, object : TIMCallBack {
                override fun onError(i: Int, s: String) {
                    Toast.makeText(this@DialogActivity, getString(R.string.login_error), Toast.LENGTH_SHORT).show()
                    logout()
                }

                override fun onSuccess() {
                    Toast.makeText(this@DialogActivity, getString(R.string.login_succ), Toast.LENGTH_SHORT).show()
                    val deviceMan = android.os.Build.MANUFACTURER
                    //注册小米和华为推送
                    finish()
                }
            })
            R.id.btnCancel -> logout()
        }
    }

    private fun logout() {
        TlsBusiness.logout(UserInfo.getInstance().id)
        UserInfo.getInstance().id = null
        FriendshipInfo.getInstance().clear()
        GroupInfo.getInstance().clear()
        val intent = Intent(this, SplashActivity::class.java)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        startActivity(intent)
    }

    /**
     * 判断小米推送是否已经初始化
     */
    private fun shouldMiInit(): Boolean {
        val am = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val processInfos = am.runningAppProcesses
        val mainProcessName = packageName
        val myPid = android.os.Process.myPid()
        for (info in processInfos) {
            if (info.pid == myPid && mainProcessName == info.processName) {
                return true
            }
        }
        return false
    }
}
